package cn.ug.activity.web.controller;

import static cn.ug.config.QueueName.QUEUE_MSG_SEND;

import cn.ug.activity.mapper.entity.CouponDonation;
import cn.ug.activity.mapper.entity.CouponMember;
import cn.ug.activity.mapper.entity.CouponRepertory;
import cn.ug.activity.service.CouponDonationService;
import cn.ug.activity.service.CouponMemberService;
import cn.ug.activity.service.CouponRepertoryService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.MemberInfoBean;
import cn.ug.msg.mq.Msg;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.util.ValidatorUtil;
import cn.ug.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static cn.ug.util.ConstantUtil.*;

@RestController
@RequestMapping("coupon/donation")
public class CouponDonationController extends BaseController {
    @Autowired
    private CouponDonationService couponDonationService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private CouponMemberService couponMemberService;
    @Autowired
    private CouponRepertoryService couponRepertoryService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        CouponDonation entity = couponDonationService.get(Integer.parseInt(id));
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/mobiles")
    public SerializeObject<String> getMobiles(String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        CouponDonation entity = couponDonationService.get(Integer.parseInt(id));
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<String>(ResultType.NORMAL, "", entity.getMobiles());
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<CouponDonation>> list(@RequestHeader String accessToken, Page page, Order order, String couponName, Integer status, Integer type, String startTime, String endTime, Integer startNum, Integer endNum) {
        couponName = UF.toString(couponName);
        status = status == null ? -1 : status;
        type = type == null ? -1 : type;
        startNum = startNum == null ? -1 : startNum;
        startNum = startNum == null ? -1 : startNum;
        endNum = endNum == null ? -1 : endNum;
        startTime = UF.toString(startTime);
        endTime = UF.toString(endTime);
        int total = couponDonationService.countRecords(couponName, status, type, startTime, endTime, startNum, endNum);
        page.setTotal(total);
        if (total > 0) {
            List<CouponDonation> list = couponDonationService.listRecords(couponName, status, type, startTime, endTime, startNum, endNum, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<CouponDonation>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<CouponDonation>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<CouponDonation>()));
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, CouponDonation entity, HttpServletRequest request) {
        if(null == entity || StringUtils.isBlank(entity.getCouponIds())) {
            return new SerializeObjectError("22000012");
        }
        entity.setCreateUserId(LoginHelper.getLoginId());
        entity.setCreateUserName(LoginHelper.getName());
        if (entity.getTargetType() != 1 && entity.getTargetType() != 2) {
            return new SerializeObjectError("22000013");
        }
        if (entity.getTimeType() == 2) {
            if (StringUtils.isBlank(entity.getDonationTime())) {
                return new SerializeObjectError("22000020");
            }
            try {
                Integer date = Integer.parseInt(StringUtils.replaceAll(entity.getDonationTime(), MINUS, BLANK));
                Integer currentDate = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()));
                if (date <= currentDate) {
                    return new SerializeObjectError("22000021");
                }
            } catch (Exception e) {
                return new SerializeObjectError("22000022");
            }
        }
        if (entity.getTargetType() == 1) {
            SerializeObject<Integer> bean = memberUserService.countTotalUsers();
            if (null == bean || bean.getCode() != ResultType.NORMAL) {
                return new SerializeObjectError("22000014");
            }
            entity.setTotalQuantity(bean.getData());
        } else {
            CommonsMultipartResolver multipartResolver  = new CommonsMultipartResolver(request.getSession().getServletContext());
            if(multipartResolver.isMultipart(request)){
                MultipartHttpServletRequest  multiRequest = (MultipartHttpServletRequest)request;
                Iterator<String> iterator = multiRequest.getFileNames();
                String mobiles = "";
                Set<String> mobileSet = new HashSet<String>();
                while(iterator.hasNext()){
                    MultipartFile file = multiRequest.getFile(iterator.next());
                    BufferedReader br= null;
                    try {
                        InputStreamReader isr = new InputStreamReader(file.getInputStream(),"utf-8");
                        br = new BufferedReader(isr);
                        String line = "";
                        int index = 0;
                        while ((line = br.readLine()) != null) {
                            index ++;
                            if(index == 1){
                                continue;
                            }
                            if(StringUtils.isNotBlank(line)){
                                if(line.split(COMMA).length == 1){
                                    if(StringUtils.isBlank(line.split(COMMA)[0])){
                                        continue;
                                    }
                                    if (ValidatorUtil.isMobile(line.split(COMMA)[0])) {
                                        mobileSet.add(line.split(COMMA)[0]);
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        return new SerializeObjectError("22000015");
                    }finally{
                        if(br!=null){
                            try{
                                br.close();
                                br=null;
                            }catch(IOException e){
                                e.printStackTrace();
                                info(e.getMessage());
                            }
                        }
                    }
                }
                if (mobileSet != null && mobileSet.size() > 0) {
                    for (String mobile : mobileSet) {
                        mobiles += mobile+COMMA;
                    }
                    mobiles = StringUtils.substring(mobiles, 0, StringUtils.length(mobiles) - 1);
                    entity.setTotalQuantity(mobileSet.size());
                    entity.setMobiles(mobiles);
                }
            }
        }
        if (entity.getId() > 0 && entity.getTargetType() == 2 && StringUtils.isBlank(entity.getMobiles())) {
            CouponDonation bean = couponDonationService.get(entity.getId());
            if (bean != null && StringUtils.isNotBlank(bean.getMobiles())) {
                entity.setMobiles(bean.getMobiles());
            }
        }
        if (couponDonationService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping(value="/status")
    public SerializeObject audit(@RequestHeader String accessToken, int id, int status, String remark) {
        CouponDonation entity = couponDonationService.get(id);
        if(null == entity || StringUtils.isBlank(entity.getCouponIds())) {
            return new SerializeObjectError("22000012");
        }
        if (entity.getStatus() != 1) {
            return new SerializeObjectError("22000019");
        }
        entity.setAuditUserId(LoginHelper.getLoginId());
        entity.setAuditUserName(LoginHelper.getName());
        entity.setStatus(status);
        entity.setRemark(remark);
        if (entity.getTimeType() == 2) {
            if (StringUtils.isBlank(entity.getDonationTime())) {
                return new SerializeObjectError("22000020");
            }
            try {
                Integer date = Integer.parseInt(StringUtils.replaceAll(entity.getDonationTime(), MINUS, BLANK));
                Integer currentDate = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()));
                if (date <= currentDate) {
                    return new SerializeObjectError("22000021");
                }
            } catch (Exception e) {
                return new SerializeObjectError("22000022");
            }
        }
        if (status == 3 && entity.getTimeType() == 1) {
            entity.setDonationTime(UF.getFormatDateTime(UF.getDateTime()));
        }
        if (couponDonationService.audit(entity)) {
            if (status == 3 && entity.getTimeType() == 1 && StringUtils.isNotBlank(entity.getCouponIds())) {
                List<Integer> ids = new ArrayList<Integer>();
                String[] idsInfo = StringUtils.split(entity.getCouponIds(), COMMA);
                if (idsInfo != null && idsInfo.length > 0) {
                    for (int i = 0; i < idsInfo.length; i++) {
                        ids.add(Integer.parseInt(idsInfo[i]));
                    }
                }
                List<CouponRepertory> couponRepertories = couponRepertoryService.findByIds(ids);
                info("优惠券赠送审核成功...");
                String mark = "";
                if (entity.getType() == 0) {
                    mark = "mg黄金红包";
                } else if (entity.getType() == 2) {
                    mark = "元商城满减券";
                }
                final String desc = mark;
                final String noticeType = entity.getNoticeType();
                if (couponRepertories != null && couponRepertories.size() > 0) {
                    SerializeObject<Integer> bean = memberUserService.countTotalUsers();
                    info("优惠券赠送获取赠送人数...");
                    if (null != bean && bean.getCode() == ResultType.NORMAL) {
                        int num = bean.getData();
                        entity.setTotalQuantity(num);
                        info("优惠券赠送获取赠送总人数:" + num);
                        int pages = PaginationUtil.getTotalPage(num, 1000);
                        EXECUTOR.execute(new Runnable(){
                            @Override
                            public void run() {
                                for (int i = 0; i < entity.getQuantity(); i++) {
                                    if (entity.getTargetType() == 1) {
                                        int page = 0;
                                        if (couponDonationService.modifyStatus(entity.getId(), 4)) {
                                            info("优惠券赠送更改赠送状态成功...");
                                            couponDonationService.save(entity);
                                            for (int j = 0; j < pages; j++) {
                                                page = j + 1;
                                                SerializeObject<DataTable<MemberInfoBean>> usersBean = memberUserService.listUserId(page, 1000);
                                                if (null != usersBean && usersBean.getCode() == ResultType.NORMAL && usersBean.getData() != null) {
                                                    List<MemberInfoBean> users = usersBean.getData().getDataList();
                                                    List<CouponMember> coupons = new ArrayList<CouponMember>();
                                                    int discountAmount = 0;
                                                    for (CouponRepertory couponRepertory : couponRepertories) {
                                                        discountAmount += couponRepertory.getDiscountAmount();
                                                    }
                                                    for (MemberInfoBean user : users) {
                                                        for (CouponRepertory couponRepertory : couponRepertories) {
                                                            CouponMember couponMember = new CouponMember();
                                                            couponMember.setAddTime(UF.getFormatDateTime(LocalDateTime.now()));
                                                            couponMember.setMemberId(user.getId());
                                                            couponMember.setCouponId(couponRepertory.getId());
                                                            coupons.add(couponMember);
                                                        }
                                                    }
                                                    couponMemberService.save(coupons);
                                                    if (entity.getIsNotice() == 2 && discountAmount > 0) {
                                                        for (MemberInfoBean user : users) {
                                                            Msg msg = new Msg();
                                                            msg.setMemberId(user.getId());
                                                            msg.setMobile(user.getMobile());
                                                            msg.setNoticeType(noticeType);
                                                            msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.GIVE_COUPON.getIndex());
                                                            Map<String, String> paramMap = new HashMap<>();
                                                            paramMap.put("couponInfo", discountAmount+desc);
                                                            msg.setParamMap(paramMap);
                                                            amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
                                                        }
                                                    }
                                                    info("优惠券赠送成功...");
                                                }
                                            }
                                        }
                                    } else {
                                        if (StringUtils.isNotBlank(entity.getMobiles())) {
                                            SerializeObject<List<MemberInfoBean>> resultBean = memberUserService.listUserId(String.valueOf(entity.getId()));
                                            if (null != resultBean && resultBean.getCode() == ResultType.NORMAL && resultBean.getData() != null) {
                                                List<MemberInfoBean> users = resultBean.getData();
                                                if (couponDonationService.modifyStatus(entity.getId(), 4)) {
                                                    info("优惠券赠送更改赠送状态成功...");
                                                    List<CouponMember> coupons = new ArrayList<CouponMember>();
                                                    entity.setTotalQuantity(users.size());
                                                    couponDonationService.save(entity);
                                                    int discountAmount = 0;
                                                    for (CouponRepertory couponRepertory : couponRepertories) {
                                                        discountAmount += couponRepertory.getDiscountAmount();
                                                    }
                                                    for (MemberInfoBean user : users) {
                                                        for (CouponRepertory couponRepertory : couponRepertories) {
                                                            CouponMember couponMember = new CouponMember();
                                                            couponMember.setAddTime(UF.getFormatDateTime(LocalDateTime.now()));
                                                            couponMember.setMemberId(user.getId());
                                                            couponMember.setCouponId(couponRepertory.getId());
                                                            coupons.add(couponMember);
                                                        }
                                                    }
                                                    couponMemberService.save(coupons);
                                                    if (entity.getIsNotice() == 2 && discountAmount > 0) {
                                                        for (MemberInfoBean user : users) {
                                                            Msg msg = new Msg();
                                                            msg.setMemberId(user.getId());
                                                            msg.setMobile(user.getMobile());
                                                            msg.setNoticeType(noticeType);
                                                            msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.GIVE_COUPON.getIndex());
                                                            Map<String, String> paramMap = new HashMap<>();
                                                            paramMap.put("couponInfo", discountAmount+desc);
                                                            msg.setParamMap(paramMap);
                                                            amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
                                                        }
                                                    }
                                                    info("优惠券赠送成功...");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            }
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }
}
